import md5 from 'md5'
import { ACCESS_KEY, SECRET_KEY } from '@/config/api'
import { typeof2, getUrlParams } from './index'

// 数据排序
// { a: { a: 1, b: 2 } }
// { a: [
//        {a: 1}
//   ]
// }
const sortData = data => {
  const result = {}
  const filterValue = [null, undefined, '']

  Object.keys(data)
    .sort()
    .forEach(key => {
      if (typeof2(data[key]) === 'object') {
        result[key] = sortData(data[key])
        return false
      }

      if (!filterValue.includes(data[key])) {
        result[key] = data[key]
      }
    })

  return result
}

// 接口验签
export function useSign (config) {
  const headers = config.headers || config.header

  headers.accessKey = ACCESS_KEY

  const reqTime = Math.floor(Date.now() / 1000)
  headers.reqTime = reqTime

  let sign = `reqTime=${reqTime}`

  const urlParams = getUrlParams(config.url)
  const assignData = Object.assign({}, urlParams, config.params, config.data)
  const data = sortData(assignData)
  const dataStr = Object.keys(data)
    .map(key => {
      if (typeof data[key] !== 'object') return `${key}=${data[key]}`

      return `${key}=${JSON.stringify(data[key])}`
    })
    .join('&')

  if (dataStr) sign += `&${dataStr}`
  sign += `&key=${SECRET_KEY}`
  console.log(sign)

  config.headers.reqTime = reqTime
  config.headers.accessKey = ACCESS_KEY
  config.headers.sign = md5(md5(sign))

  return config
}
